import { ref } from "vue";
import { useDrag, UseDragOptions } from "./useDrag";
import { Point } from "/@/components/types";
import { getPointDeg } from "/@/utils/draw";

type UseRotateOptions<T, K> = UseDragOptions<T, K> & {
  centerPoint: Point | (() => Point);
};

type RotateStartResult = Record<string, any> & { rotate: number };

/**
 * 用于foreignObject包着svg图标的元素触发的旋转
 */
export function useRotate<T extends any[]>({
  getRelativeElement,
  centerPoint,
  start,
  move,
  end,
}: UseRotateOptions<T, RotateStartResult | void>) {
  const rotate = ref(0);
  const { dragStart: rotateStart } = useDrag<T, RotateStartResult>({
    getRelativeElement,
    start(startData, e) {
      e.preventDefault();
      let startResult = {
        rotate: rotate.value,
      };
      if (start) {
        Object.assign(startResult, start(startData, e) || {});
      }
      return startResult;
    },
    move(data, e) {
      const { offsetX, offsetY, startData, startResult } = data;
      const deg = getPointDeg(typeof centerPoint == "function" ? centerPoint() : centerPoint, startData, {
        x: offsetX,
        y: offsetY,
      });
      rotate.value = (startResult.rotate + deg) % 360;
      move && move(data, e);
    },
    end(data, e) {
      end && end(data, e);
    },
  });
  return {
    rotateStart,
    rotate,
  };
}
